package com.mall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mall.cart.feign.CartFeign;
import com.mall.cart.model.Cart;
import com.mall.goods.feign.SkuFeign;
import com.mall.order.model.Order;
import com.mall.order.mapper.OrderMapper;
import com.mall.order.model.OrderSku;
import com.mall.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mall.order.service.IOrderSkuService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Darren
 * @since 2022-08-29
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private CartFeign cartFeign;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private IOrderSkuService orderSkuService;

    @Override
    @GlobalTransactional
    public boolean addOrder(Order order) {
        // 1、根据用户勾选的购物车ID查询购物车记录
        List<Cart> cartList = cartFeign.list(order.getCartIds()).getData();
        if (cartList == null || cartList.size() == 0)
            return false;

        // 2、实现库存递减
        skuFeign.reduceSkuNum(cartList);

        // 3、库存递减成功后，将购物车商品存入到订单明细中
        int totalNum = 0;
        int totalMoney = 0;
        List<OrderSku> orderSkuList = new ArrayList<>();
        for (Cart cart : cartList) {
            OrderSku orderSku = JSON.parseObject(JSON.toJSONString(cart), OrderSku.class);
            orderSku.setOrderId(order.getId());
            orderSku.setId(IdWorker.getIdStr());
            orderSku.setMoney(orderSku.getPrice() * orderSku.getNum());
            orderSkuList.add(orderSku);
            // 统计数据
            totalNum += orderSku.getNum();
            totalMoney += orderSku.getMoney();
        }
        boolean b = orderSkuService.saveBatch(orderSkuList);
        if (!b)
            return false;

        // 4、添加订单
        order.setTotalNum(totalNum);
        order.setMoneys(totalMoney);
        boolean save = this.save(order);
        if (!save)
            return false;

        // 5、删除当前操作的购物车数据
        cartFeign.deleteCart(order.getCartIds());

        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteById(String id) {
        return super.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean updateOrder(Order order) {
        return super.updateById(order);
    }

    @Override
    public Order getById(String id) {
        return super.getById(id);
    }

    @Override
    public List<Order> selectList(Order order) {
        return super.list(getQueryWrapper(order));
    }

    @Override
    public Page<Order> selectPage(Page<Order> page, Order order) {
        return super.page(page, getQueryWrapper(order));
    }

    public LambdaQueryWrapper<Order> getQueryWrapper(Order order) {
        return Wrappers.<Order>lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(order.getId()), Order::getId, order.getId())
                .eq(ObjectUtils.isNotEmpty(order.getTotalNum()), Order::getTotalNum, order.getTotalNum())
                .eq(ObjectUtils.isNotEmpty(order.getMoneys()), Order::getMoneys, order.getMoneys())
                .eq(ObjectUtils.isNotEmpty(order.getPayType()), Order::getPayType, order.getPayType())
                .eq(ObjectUtils.isNotEmpty(order.getPayTime()), Order::getPayTime, order.getPayTime())
                .eq(ObjectUtils.isNotEmpty(order.getConsignTime()), Order::getConsignTime, order.getConsignTime())
                .eq(ObjectUtils.isNotEmpty(order.getEndTime()), Order::getEndTime, order.getEndTime())
                .eq(ObjectUtils.isNotEmpty(order.getUsername()), Order::getUsername, order.getUsername())
                .eq(ObjectUtils.isNotEmpty(order.getRecipients()), Order::getRecipients, order.getRecipients())
                .eq(ObjectUtils.isNotEmpty(order.getRecipientsMobile()), Order::getRecipientsMobile, order.getRecipientsMobile())
                .eq(ObjectUtils.isNotEmpty(order.getRecipientsAddress()), Order::getRecipientsAddress, order.getRecipientsAddress())
                .eq(ObjectUtils.isNotEmpty(order.getWeixinTransactionId()), Order::getWeixinTransactionId, order.getWeixinTransactionId())
                .eq(ObjectUtils.isNotEmpty(order.getOrderStatus()), Order::getOrderStatus, order.getOrderStatus())
                .eq(ObjectUtils.isNotEmpty(order.getPayStatus()), Order::getPayStatus, order.getPayStatus())
                .eq(ObjectUtils.isNotEmpty(order.getIsDelete()), Order::getIsDelete, order.getIsDelete())
                ;
    }
}
